package com.comunity_cloud.client.model.file_list;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import com.comunity_cloud.client.model.communication.packet.PeerPacketHeader;

public class SendMeFilesResponse extends PeerPacketHeader{

	private List<FileInfo> files;
	private byte[] byteArray;
	
	public static class FileInfo implements Serializable{
		
		public long fileSize;
		
		public String fileName;
		
		public byte[] image;
		
		public long version;
		
		public long chunkSize;
		
		public boolean isPrimary;
		
		public long totalOffset;
	}
	
	public SendMeFilesResponse() {
		this.type = Type.SEND_ME_FILES_RESPONSE;
	}
		
	@Override
	protected void convertToBytes() {
		byteBuffer.put(byteArray);
	}

	@Override
	protected int headerLength() {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(out);
			oos.writeObject(files);
			byteArray = out.toByteArray();
			return byteArray.length;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void fromBytes() {
		try {
			ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes, byteBuffer.position(), headerLength));
			files = (List<FileInfo>) in.readObject();
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public List<FileInfo> getFiles() {
		return files;
	}
	
	public void addFile(FileInfo file) {
		if (files == null) {
			files = new LinkedList<>();
		}
		files.add(file);
	}
}
